package com.fancy.learncenter.activity;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.fancy.learncenter.bean.BaseDataBean;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.net.IdeaObserver;
import com.fancy.learncenter.utils.DimenUtil;
import com.fancy.learncenter.utils.PermissionUtils;
import com.fancy.learncenter.utils.ToastUtil;
import com.fancy.learncenter.utils.Utils;
import com.fancy.learncenter.view.CustomProgressDialog;
import com.fancy.learncenter.view.LPopWindow;
import com.fancy.learncenter.view.LiZhiDialog;
import com.fancy.learncenter.view.PopupWindowCity;
import com.fancy.learncenter.view.PopupWindowCutPic;
import com.fancy.learncenter.view.PopupWindowWriteInfo;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;
import com.superservice.lya.R;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ReleaseHuoDongActivity extends TakePhotoActivity {
    private static final int ACCESS_LOCATION_RESULT_CODE = 100100;


    @Bind(R.id.next)
    TextView next;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.start_time)
    TextView startTime;
    @Bind(R.id.end_tome)
    TextView endTome;
    @Bind(R.id.location_tv)
    TextView locationTv;
    @Bind(R.id.location_rl)
    RelativeLayout locationRl;
    @Bind(R.id.detail_location_tv)
    EditText detailLocationTv;
    @Bind(R.id.money_tv)
    EditText moneyTv;
    @Bind(R.id.simpleDraweeView)
    SimpleDraweeView simpleDraweeView;
    @Bind(R.id.description)
    EditText description;
    @Bind(R.id.act_contact)
    EditText actContact;
    @Bind(R.id.act_mobile)
    EditText actMobile;
    @Bind(R.id.act_title)
    EditText actTitle;
    @Bind(R.id.rootView)
    RelativeLayout rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_huodong);
        ButterKnife.bind(this);
        title.setText("发布活动");
        next.setText("发布");

        popupWindowCity = new PopupWindowCity(this);
        popupWindowCity.setSelectCallBack(new PopupWindowCity.SelectCallBack() {
            @Override
            public void selectCallBack(String province, String city, String area, String locationId) {
                locationTv.setText(province + city + area);
                locId = locationId;
            }

        });
        takePhoto = getTakePhoto();
        takePhoto.onEnableCompress(Utils.takePhotoCompress(), true);

        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
//                btn_Time.setText(getTime(date));
//                Button btn = (Button) v;
//                btn.setText(getTime(date));
                startTime.setText(Utils.getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .build();
        edTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
//                btn_Time.setText(getTime(date));
//                Button btn = (Button) v;
//                btn.setText(getTime(date));
                endTome.setText(Utils.getTime(date));
            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})
                .build();

    }

    TimePickerView pvTime;
    TimePickerView edTime;
    PopupWindowCity popupWindowCity;

    @OnClick({R.id.back, R.id.next, R.id.start_time, R.id.end_tome, R.id.location_rl, R.id.simpleDraweeView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
//                LiZhiDialog.show(this, R.mipmap.bg_tuxing, "退出前，您需要保存吗？",
//                        true, "不保存", "保存", new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                finish();
//                                LiZhiDialog.dismissDialog();
//                            }
//                        }, new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                finish();
//                                LiZhiDialog.dismissDialog();
//                            }
//                        });
                break;
            case R.id.next:
                submit();
                break;
            case R.id.start_time:
                pvTime.show();
                break;
            case R.id.end_tome:
                edTime.show();
                break;
            case R.id.location_rl:
                popupWindowCity.ShowPickerView();
                break;
            case R.id.simpleDraweeView:

                if (popupWindowCutPic == null) {
                    popupWindowCutPic = new PopupWindowCutPic(rootView);
                    popupWindowCutPic.setOnClickListener(new PopupWindowCutPic.CutPicCallBack() {
                        @Override
                        public void choose() {
                            takePhoto.onPickFromGalleryWithCrop(Utils.getCutPicPath(), Utils.getCutPicCropOptions());
                        }

                        @Override
                        public void cancel() {

                        }

                        @Override
                        public void camera() {
                            takePhoto.onPickFromCaptureWithCrop(Utils.getCutPicPath(), Utils.getCutPicCropOptions());
                        }

                        @Override
                        public void see() {

                        }
                    });

                }

                popupWindowCutPic.isShow();
                break;
        }
    }


    PopupWindowCutPic popupWindowCutPic;

    TakePhoto takePhoto;


    //分享弹出框
    LPopWindow lPopWindow;

    private void showPicPopWindow(View view) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pupopwinodw_edit_price, null);
        lPopWindow = new LPopWindow.Builder(ReleaseHuoDongActivity.this)
                .setView(contentView)
                .size(ViewGroup.LayoutParams.MATCH_PARENT, DimenUtil.dip2px(360))
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.7f) // 控制亮度
                .build()
                .showAtLocation(view, Gravity.BOTTOM, 0, 0);
    }

    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_ACCESS_FINE_LOCATION:
                    //权限被允许（如果被拒绝的话就会提示去设置中打开权限）
                    startActivityForResult(new Intent(ReleaseHuoDongActivity.this, MapLocationActivity.class), ACCESS_LOCATION_RESULT_CODE);
                    break;
            }
        }
    };


    /**
     * 定位权限授权回调
     */
    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }


    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        if (result.getImage() != null && !TextUtils.isEmpty(result.getImage().getCompressPath())) {

            picPath = result.getImage().getCompressPath();
            simpleDraweeView.setImageURI(Uri.fromFile(new File(result.getImage().getCompressPath())));
        }
    }

    String picPath = "";
    String locId = "";


    Dialog dialog;
    boolean isSubmit = false;

    private void disDia() {

        isSubmit = false;
        if (dialog != null) {
            dialog.dismiss();
        }
    }


    private void submit() {

        if (isSubmit) {
            return;
        } else {
            isSubmit = true;
            if (dialog == null) {
                dialog = CustomProgressDialog.creatRequestDialog(this);
            }
            dialog.show();
        }


        Map maps = new HashMap();

        maps.put("poster", "data:image/jpeg;base64," + Utils.imageToBase64(picPath));
        maps.put("title", actTitle.getText().toString());
        maps.put("content", description.getText().toString());
        maps.put("beginTime", startTime.getText().toString());
        maps.put("endTime", endTome.getText().toString());
        maps.put("locationId", locId);
        maps.put("place", detailLocationTv.getText().toString());
        maps.put("fee", moneyTv.getText().toString());
        maps.put("contactName", actContact.getText().toString());
        maps.put("contact", actMobile.getText().toString());
        maps.put("status", "0");


        HttpMehtod.getInstance().releaseActivity(maps, new IdeaObserver<BaseDataBean>() {

            @Override
            public void onSuccess(BaseDataBean stringBaseDataBean) {
                ToastUtil.show("发布成功");
                disDia();
                finish();
            }

            @Override
            public void onFail(int errorCode) {
                disDia();
            }

        });

    }


}
